<?php

/*
	info: 商家列表页
	date: 2011-12-18
*/

define('PAGESCRIPT', 'company');
define('USER_LOGIN_CHECK', TRUE);
require dirname(__FILE__).'/include/common.inc.php';

$webglobal['file_company'] = array();

if ($webglobal['action'] == 'view') {
	$id = isset($webrequest['id']) && $webrequest['id'] ? intval($webrequest['id']) : 0;
	if (!$id) {
		global_ShowMessage('对不起,系统中没有该热门商家!');
	}
	
	$webglobal['file_company']['companyData'] = cache_GetCompanyDetail($id);
	if (!$webglobal['file_company']['companyData']['company']) {
		global_ShowMessage('对不起,系统中没有该商家!');
	}

	if ($webglobal['file_company']['companyData']['company']['image'] != '') {
		$webglobal['file_company']['companyData']['company']['thumbnail'] = array(
			'big' => getThumbnails($webglobal['file_company']['companyData']['company']['image'], 'big'),
			'small' => getThumbnails($webglobal['file_company']['companyData']['company']['image'], 'small'),
			'middle' => getThumbnails($webglobal['file_company']['companyData']['company']['image'], 'middle')
		);
	}

	//统计评分
	$scoreData = $db->GetOne("SELECT AVG(score) AS avg FROM {$webconfig['dbpre']}company_comment WHERE company_id = " . $webrequest['id'] . ' AND status = 1');
	
	$webglobal['file_company']['companyData']['score_avg'] = number_format($scoreData['avg'], 1);
	//查询商家发布的优惠劵
	/*
	$query = $db->Query("SELECT * FROM {$webconfig['dbpre']}coupon WHERE company_id = '{$id}' AND status = 1");
	while ($tempdata = $db->FetchArray($query)) {
		$tempdata['starttime_show'] = !empty($tempdata['starttime']) ? global_FormatTime($tempdata['starttime'], 'Y年n月j日') : '';
		$tempdata['endtime_show'] = !empty($tempdata['endtime']) ? global_FormatTime($tempdata['endtime'], 'Y年n月j日') : '';
		$tempdata['pubtime_show'] = !empty($tempdata['pubtime']) ? global_FormatTime($tempdata['pubtime']) : '';

		$tempdata['discount'] = $tempdata['original'] > 0 ? number_format(($tempdata['price'] / $tempdata['original']) * 10, 1) : 0;
		$tempdata['discount_num'] = number_format(($tempdata['original'] - $tempdata['price']), 1);
		$cacheData[$cacheKey]['coupon'][$tempdata['id']] = $tempdata;
	}
	*/
	$tempsearchsql = " WHERE status=1 AND company_id = ".$id;
	$webglobal['file_coupon'] = array();
	$webrequest['page'] = isset($webrequest['page']) ? max(1, intval($webrequest['page'])) : 1;
	$webglobal['file_coupon']['perpage'] = 6;
	$webglobal['file_coupon']['datanum'] = $db->GetNum("SELECT COUNT(*) FROM {$webconfig['dbpre']}coupon{$tempsearchsql}");

	if ($webglobal['file_coupon']['datanum'] > 0) {
		$curoptions['page'] = '@@';
		$webglobal['page'] = global_Page($webglobal['file_coupon']['datanum'], $webglobal['file_coupon']['perpage'], $webrequest['page'], WEBURLPATH."/company.php?action=view&id={$id}&page=@@");

		$tempstartnum = ($webrequest['page']-1)*$webglobal['file_coupon']['perpage'];
		$temporderstr = "pubtime DESC";

		$query = $db->Query("SELECT * FROM {$webconfig['dbpre']}coupon{$tempsearchsql} ORDER BY {$temporderstr} LIMIT $tempstartnum, {$webglobal['file_coupon']['perpage']}");
		$temptr = 1;
		$webglobal['file_coupon']['dataarray'] = array();

		while ($tempdata = $db->FetchArray($query)) {
			$tempdata['starttime_show'] = !empty($tempdata['starttime']) ? global_FormatTime($tempdata['starttime'], 'Y年n月j日') : '';
			$tempdata['endtime_show'] = !empty($tempdata['endtime']) ? global_FormatTime($tempdata['endtime'], 'Y年n月j日') : '';
			$tempdata['pubtime_show'] = !empty($tempdata['pubtime']) ? global_FormatTime($tempdata['pubtime']) : '';
			if ($tempdata['image']) {
				$tempdata['thumbnail'] = array(
					'big' => getThumbnails($tempdata['image'], 'big'),
					'small' => getThumbnails($tempdata['image'], 'small'),
					'middle' => getThumbnails($tempdata['image'], 'middle')
				);
			}
			$webglobal['file_coupon']['dataarray'][$tempdata['id']] = $tempdata;
		}
	}

	$newsCategoryDataModel = CategoryDataModel::factory('news', array('cache' => true));
	//获取热门新闻
	$hot = array(
		'orderby' => 'click',
		'row' => 10,
		'typeid' => 2
	);
	$webglobal['file_company']['hot'] = getArcList($hot);
//查看大地图
} elseif ($webglobal['action'] == 'viewmap') {
	$id = isset($webrequest['id']) ? intval($webrequest['id']) : 0;
	$webglobal['file_company']['companyData'] = cache_GetCompanyDetail($id);
	if ($webglobal['file_company']['companyData']) {
		template_Display('company_map');
		exit();
	}
//收藏
} elseif ($webglobal['action'] == 'collect') {
	$webrequest['id'] = isset($webrequest['id']) ? intval($webrequest['id']) : 0;
	$webglobal['file_company']['companyData'] = cache_GetCompanyDetail($webrequest['id']);
	if (!$webglobal['file_company']['companyData']) {
		global_ShowMessage('参数错误。');
	}
	if ($user['base_uid']<=0)
	{
		global_ShowMessage("请登录后操作。", WEBURLPATH.'/login.php?gourl='.urlencode(WEBURLPATH."/company.php?action=view&id={$webrequest['id']}"));
	}
	if ($user['base_type']!=0)
	{
		global_ShowMessage("只有个人用户才能收藏！", '', 'BACK');
	}
	$webglobal['datainfo'] = $db->GetOne("SELECT * FROM {$webconfig['dbpre']}company_favorites WHERE company_id='{$webrequest['id']}' AND user_id='{$user['base_uid']}'");
	if (!empty($webglobal['datainfo']))
	{
		global_ShowMessage("您已经收藏了该店铺。", '', 'BACK');
	}
	$db->Insert('company_favorites', array(
						'company_id' => $webrequest['id'],
						'user_id' => $user['base_uid'],
						'addtime' => $webserver['timestamp'],
					), TRUE);
	$db->Update('company', "favorites_num=favorites_num+1", "id='{$webrequest['id']}'");
	global_ShowMessage("恭喜您，收藏成功！", WEBURLPATH."/company.php?action=view&id={$webrequest['id']}");
} else {
	//获取参数
	$webrequest['page'] = isset($webrequest['page']) ? max(1, intval($webrequest['page'])) : 1;

	$webrequest['c'] = isset($webrequest['c']) && $webrequest['c'] ? intval($webrequest['c']) : 0; //商家分类ID
	$webrequest['a'] = isset($webrequest['a']) && $webrequest['a'] ? intval($webrequest['a']) : 0; //商圈ID
	$webrequest['s'] = isset($webrequest['s']) && $webrequest['s'] ? trim($webrequest['s']) : ''; //搜索条件
	$webrequest['l'] = isset($webrequest['l']) && $webrequest['l'] ? intval($webrequest['l']) : 10; //显示条数

	$options = array();
	foreach (array('c', 'a', 's', 'l') as $field) {
		if (isset($webrequest[$field]) && $webrequest[$field]) {
			$options[$field] = $webrequest[$field];
		}
	}

	$webglobal['file_company']['urlParams'] = $options;

	$webglobal['file_company']['pageLimit'] = array();
	//按显示个数链接
	foreach (array(10, 20, 30) as $tempLimit) {
		$curoptions = $options;
		$curoptions['l'] = $tempLimit;
		$checked = false;

		if ($webrequest['l'] && $webrequest['l'] == $tempLimit) {
			$checked = true;
		}
		$webglobal['file_company']['pageLimit'][] = array(
			'title'   => $tempLimit,
			'url'     => buildURLForModule('company.php', $curoptions),
			'checked' => $checked
		);
	}

	//获取城市商圈
	$webglobal['file_company']['areadata'] = array();
	if (isset($webglobal['curcityid']) && $webglobal['curcityid']) {
		if ($areadata = $areaDataModel->getChildForLayer($webglobal['curcityid'], 2, false)) {
			foreach ($areadata as $key => $value) {
				$curoptions = $options;
				$curoptions['a'] = $value['id'];
				$value['url'] = buildURLForModule('company.php', $curoptions);
				if (isset($webglobal['file_company']['areadata'][$value['upid']])) {
					$webglobal['file_company']['areadata'][$value['upid']]['second'][$value['id']] = $value;
				} else {
					$webglobal['file_company']['areadata'][$value['id']] = $value;
					$webglobal['file_company']['areadata'][$value['id']]['second'] = array();
				}
			}
		}
	}
	//获取所选择的商圈
	$webglobal['file_company']['selectarea'] = array();
	if ($webrequest['a']) {
		$webglobal['file_company']['selectarea'][] = $webrequest['a'];
		if ($selectArea = $areaDataModel->getItem($webrequest['a'])) {
			$webglobal['file_company']['selectarea'] = array_merge($webglobal['file_company']['selectarea'], $selectArea['upCategoryID']);
		}
	}

	//全部分类链接地址
	$curoptions = $options;
	unset($curoptions['a']);
	$webglobal['file_company']['allAreaUrl'] = buildURLForModule('company.php', $curoptions);

	//全部分类链接地址
	$curoptions = $options;
	unset($curoptions['c']);
	$webglobal['file_company']['allCategoryUrl'] = buildURLForModule('company.php', $curoptions);

	//商家分类变量 $webglobal['companyCategory']
	foreach ($webglobal['companyCategory'] as $cateroyid => $category) {
		$curoptions = $options;
		$curoptions['c'] = $cateroyid;
		$url = buildURLForModule('company.php', $curoptions);
		$webglobal['companyCategory'][$cateroyid]['url'] = $url;
		if ($category['second']) {
			foreach ($category['second'] as $subcategoryid => $subcategory) {
				$suboptions = $options;
				$suboptions['c'] = $subcategoryid;
				$suburl = buildURLForModule('company.php', $suboptions);
				$webglobal['companyCategory'][$cateroyid]['second'][$subcategoryid]['url'] = $suburl;
			}
		}
	}

	//获取所选择的分类
	$webglobal['file_company']['selectcategory'] = array();
	if ($webrequest['c']) {
		$webglobal['file_company']['selectcategory'][] = $webrequest['c'];
		if ($selectCategory = $companyCategoryDataModel->getItem($webrequest['c'])) {
			$webglobal['file_company']['selectcategory'] = array_merge($webglobal['file_company']['selectcategory'], $selectCategory['upCategoryID']);
		}
	}

	//组合查询条件
	$tempsearchsql = array('status = 1');
	if (isset($webglobal['curcityid']) && $webglobal['curcityid'] && !$webrequest['a']) {
		$tempsearchsql[] = "city = " . $webglobal['curcityid'];
	}

	if ($webrequest['c']) {
		if ($subCategory = $companyCategoryDataModel->getChildForLayer($webrequest['c'], 0)) {
			$categoryID = array_keys($subCategory);
			$tempsearchsql[] = "company_category_id IN (" .implode(',', $categoryID). ")";
		}
	}
	if ($webrequest['a']) {
		if ($subArea = $areaDataModel->getChildForLayer($webrequest['a'], 0)) {
			$areaID = array_keys($subArea);
			$tempsearchsql[] = "area_id IN (" .implode(',', $areaID). ")";
		}
	}

	if ($webrequest['s']) {
		$tempsearchsql[] = $db->BuildSearchSql($webrequest['s'], array('name','description', 'address'));
	}

	$tempsearchsql = empty($tempsearchsql) ? '' : ' WHERE '.implode(' AND ', $tempsearchsql);

	$webglobal['file_company']['perpage'] = $webrequest['l'];
	$webglobal['file_company']['datanum'] = $db->GetNum("SELECT COUNT(*) FROM {$webconfig['dbpre']}company{$tempsearchsql}");

	if ($webglobal['file_company']['datanum'] > 0) {
		$options['page'] = '@@';
		$webglobal['page'] = global_Page($webglobal['file_company']['datanum'], $webglobal['file_company']['perpage'], $webrequest['page'], buildURLForModule('company.php', $options));

		$tempstartnum = ($webrequest['page']-1)*$webglobal['file_company']['perpage'];
		$temporderstr = "addtime DESC";

		$query = $db->Query("SELECT * FROM {$webconfig['dbpre']}company{$tempsearchsql} ORDER BY {$temporderstr} LIMIT $tempstartnum, {$webglobal['file_company']['perpage']}");
		$webglobal['file_company']['dataarray'] = array();

		while ($tempdata = $db->FetchArray($query)) {
			$tempdata['description'] = global_CutStr(strip_tags($tempdata['description']), 150);
			if ($tempdata['image'] != '') {
				$tempdata['thumbnail'] = array(
					'big' => getThumbnails($tempdata['image'], 'big'),
					'small' => getThumbnails($tempdata['image'], 'small'),
					'middle' => getThumbnails($tempdata['image'], 'middle')
				);
			}
			$webglobal['file_company']['dataarray'][$tempdata['id']] = $tempdata;
		}
	}

	$newsCategoryDataModel = CategoryDataModel::factory('news', array('cache' => true));
	//获取热门新闻
	$hot = array(
		'orderby' => 'click',
		'row' => 10,
		'typeid' => 2
	);
	$webglobal['file_company']['hot'] = getArcList($hot);
}

template_Display('company');
